package com.charonmc.utils;

import com.charonmc.CharonCore;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.injector.GamePhase;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import org.bukkit.Bukkit;

import java.util.ArrayList;
import java.util.List;

public class PacketManager extends PacketAdapter {
    public PacketManager() {
        super(PacketAdapter.params()
                .listenerPriority(ListenerPriority.NORMAL)
                .serverSide()
                .clientSide()
                .optionAsync()
                .gamePhase(GamePhase.PLAYING)
                .types(PacketType.Play.Server.PLAYER_INFO)
                .plugin(CharonCore.instance));
    }

    @Override
    public void onPacketSending(PacketEvent event) {
        if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
            PacketContainer packet = event.getPacket();
            final List<PlayerInfoData> data = packet.getPlayerInfoDataLists().read(0);
            if (data == null) {
                return;
            }
            final ArrayList<PlayerInfoData> profiles = new ArrayList<>();
            for (final PlayerInfoData info : data) {
                final WrappedGameProfile profile = info.getProfile();
                WrappedGameProfile newProfile;
                if (Bukkit.getPlayer(profile.getUUID()) != null) {
                    String nick = Bukkit.getPlayer(profile.getUUID()).getDisplayName();
                    newProfile = profile.withName(nick.substring(0, Math.min(nick.length(), 16)));
                } else {
                    newProfile = profile;
                }
                final PlayerInfoData newData = new PlayerInfoData(newProfile, info.getLatency(), info.getGameMode(), info.getDisplayName());
                profiles.add(newData);
            }
            packet.getPlayerInfoDataLists().write(0, profiles);
        }
    }
}